﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;

namespace MiniTennis
{
    public partial class FrmLogin : Form
    {
        private SQLiteConnection ObjConnection;
        private FrmInicio Inicio;

        public FrmLogin(FrmInicio frminicio, SQLiteConnection ObjConn)
        {
            InitializeComponent();
            ObjConnection = ObjConn;
            Inicio = frminicio;
        }

        private void btn_aceptar_Click(object sender, EventArgs e)
        {
            if (Validar_Usuario(txt_usuario.Text.Trim().ToLower(), md5(txt_password.Text.Trim())))
            {
                FrmMiniTennis tennis = new FrmMiniTennis(txt_usuario.Text.Trim().ToLower(), ObjConnection);
                tennis.Show();

                this.Hide();
            }
            else
                MessageBox.Show("Usuario/password No valido!!");

        }

        public string md5(string password)
        {
            //Declaraciones
            System.Security.Cryptography.MD5 md5;
            md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            //Conversion
            Byte[] encodedBytes = md5.ComputeHash(ASCIIEncoding.Default.GetBytes(password));  //genero el hash a partir de la password original

            //Resultado

            //return BitConverter.ToString(encodedBytes);      //esto, devuelve el hash con "-" cada 2 char
            return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(encodedBytes).ToLower(), @"-", "");     //devuelve el hash continuo y en minuscula. (igual que en php)
        }

        public Boolean Validar_Usuario(String usu,String password)
        {
            String Sql = "select usu_id from usuario where usu_id = '" + usu + "' and usu_password = '"+password+"'";
            SQLiteCommand ObjCommand = new SQLiteCommand(Sql, ObjConnection);
            ObjCommand.CommandType = CommandType.Text;
            SQLiteDataAdapter ObjDataAdapter = new SQLiteDataAdapter(ObjCommand);
            DataSet dataSet = new DataSet();

            ObjDataAdapter.Fill(dataSet, "consultoras");

            if (dataSet.Tables["consultoras"].Rows.Count > 0)
                return true;
            else
                return false;

        }

        private void btn_cancelar_Click(object sender, EventArgs e)
        {
            this.Close();
            Inicio.Show();
        } 
    }
}
